'use client';

import { useState, useEffect } from 'react';
import { useRouter } from 'next/navigation';
import { use } from 'react';
import Layout from '../../../components/Layout';
import DietRecordForm from '../../../components/DietRecordForm';
import { IconLoader2 } from '@tabler/icons-react';

export default function EditDietRecord({ params }: { params: Promise<{ id: string }> }) {
  const resolvedParams = use(params);
  const router = useRouter();
  const [loading, setLoading] = useState(true);
  const [record, setRecord] = useState<any>(null);
  const [error, setError] = useState('');

  useEffect(() => {
    const fetchRecord = async () => {
      try {
        const res = await fetch(`/api/diet/record/${resolvedParams.id}`, {
          credentials: 'include',
        });
        const data = await res.json();
        
        if (!res.ok) {
          throw new Error(data.message || '获取记录失败');
        }
        
        if (data.record) {
          setRecord(data.record);
        } else {
          setError('记录不存在');
        }
      } catch (err) {
        console.error('获取记录失败:', err);
        setError(err instanceof Error ? err.message : '获取记录失败');
      } finally {
        setLoading(false);
      }
    };

    fetchRecord();
  }, [resolvedParams.id]);

  if (loading) {
    return (
      <Layout>
        <div className="flex justify-center items-center min-h-[60vh]">
          <IconLoader2 className="w-6 h-6 animate-spin text-blue-600" />
        </div>
      </Layout>
    );
  }

  if (error || !record) {
    return (
      <Layout>
        <div className="max-w-4xl mx-auto px-4">
          <div className="bg-red-50 text-red-600 p-4 rounded-lg">
            {error || '记录不存在'}
          </div>
        </div>
      </Layout>
    );
  }

  return (
    <Layout>
      <DietRecordForm
        mode="edit"
        initialData={{
          id: record.id,
          date: new Date(record.date).toISOString().split('T')[0],
          mealType: record.mealType,
          foods: record.foods,
        }}
      />
    </Layout>
  );
} 